<script setup lang="ts">
import {ref, onMounted, onUnmounted} from 'vue';
import {ElMessage} from 'element-plus';
import SlideVerify from 'vue3-slide-verify';
import "vue3-slide-verify/dist/style.css";
import Check from "../../../assets/icons/Check.vue";
import {UserControllerService, ValidateCodeControllerService} from "../../../../generated";

const props = defineProps<{
  modelValue: boolean
}>();

const emit = defineEmits(['update:modelValue', 'close', 'success']);

const nextStepDisabled = ref(true);
const activeStep = ref(1);
const verificationCode = ref('');
const countryCode = ref('+86');
const phoneNumber = ref('');
const phoneVerificationCode = ref('');
const showSlider = ref(false);

// 发送验证码相关
const countDown = ref(0);
const timer = ref<number | null>(null);

const startCountDown = () => {
  countDown.value = 60;
  timer.value = window.setInterval(() => {
    countDown.value--;
    if (countDown.value <= 0) {
      if (timer.value) {
        clearInterval(timer.value);
        timer.value = null;
      }
    }
  }, 1000);
};

const resetCountDown = () => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
  countDown.value = 0;
};

const handleVerificationClick = () => {
  if (countDown.value > 0) return;
  showSlider.value = true;
};

const handleSliderSuccess = async () => {
  showSlider.value = false;
  nextStepDisabled.value = false
  // 这里应该调用获取验证码的API
  let res = await ValidateCodeControllerService.generateModifyPhoneCodeUsingPost({
    type: 0,
    phone: phoneNumber.value
  });
  if (res.code === 0) {
    startCountDown();
    ElMessage.success('验证码已发送，请查收');
  } else {
    ElMessage.error(res.message || '发送验证码失败')
  }
};

const getPhoneVerificationCode = async () => {
  if (!phoneNumber.value) {
    ElMessage.warning('请输入手机号');
    return;
  }
  let res = await ValidateCodeControllerService.generateModifyPhoneCodeUsingPost({
    type: 1,
    phone: phoneNumber.value
  });
  if (res.code === 0 && res.data) {
    startCountDown();
    ElMessage.success('验证码已发送，请查收');
  } else {
    ElMessage.error(res.message || '发送验证码失败')
  }
};

const nextStep = async () => {
  if (!verificationCode.value) {
    ElMessage.warning('请输入验证码');
    return;
  }
  let res = await UserControllerService.modifyPhoneUsingPost({
    type: 0,
    phone: phoneNumber.value,
    code: verificationCode.value
  });
  if (res.code === 0 && res.data) {
    activeStep.value = 2;
    phoneNumber.value = '';
    phoneVerificationCode.value = '';
    resetCountDown()
  } else {
    ElMessage.error(res.message || '验证码错误')
  }
};

const confirmChange = async () => {
  if (!phoneNumber.value) {
    ElMessage.warning('请输入手机号');
    return;
  }

  if (!phoneVerificationCode.value) {
    ElMessage.warning('请输入验证码');
    return;
  }
  let res = await UserControllerService.modifyPhoneUsingPost({
    type: 1,
    phone: phoneNumber.value,
    code: phoneVerificationCode.value
  });
  if (res.code === 0 && res.data) {
    emit('success');
    handleClose();
  } else {
    ElMessage.error(res.message || '验证码错误')
  }
};

const handleClose = () => {
  activeStep.value = 1;
  verificationCode.value = '';
  phoneNumber.value = '';
  phoneVerificationCode.value = '';
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
  emit('update:modelValue', false);
  emit('close');
};

// 处理点击遮罩层关闭
const handleMaskClick = (e: MouseEvent) => {
  if ((e.target as HTMLElement).classList.contains('dialog-mask')) {
    handleClose();
  }
};

// 处理ESC键关闭
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Escape') {
    handleClose();
  }
};

onMounted(() => {
  document.addEventListener('keydown', handleKeyDown);
});

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown);
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<template>
  <Teleport to="body">
    <div v-if="props.modelValue" class="dialog-container">
      <div class="dialog-mask" @click="handleMaskClick">
        <div class="dialog-content">
          <div class="steps">
            <div class="step-item" :class="{ active: activeStep === 1 }">
              <div class="step-number">
                <template v-if="activeStep === 2">
                  <Check/>
                </template>
                <template v-else>1</template>
              </div>
              <div class="step-text">解绑当前手机号</div>
            </div>
            <div class="step-line"></div>
            <div class="step-item" :class="{ active: activeStep === 2 }">
              <div class="step-number">2</div>
              <div class="step-text">绑定新手机号</div>
            </div>
          </div>

          <div class="dialog-body">
            <div v-if="activeStep === 1" class="step-container">
              <span class="dialog-body-title">解绑当前手机号</span>
              <div class="form-container">
                <div class="phone-input-group">
                  <el-select v-model="countryCode" class="country-code">
                    <el-option label="+86" value="+86"/>
                  </el-select>
                  <el-input v-model="phoneNumber" placeholder="请输入已绑定的手机号"/>
                </div>
                <div class="verification-input-group">
                  <template v-if="!showSlider">
                    <el-input v-model="verificationCode" placeholder="请输入手机验证码">
                      <template #suffix>
                        <span
                            class="verification-code-btn"
                            :class="{ 'disabled': countDown > 0 }"
                            @click="handleVerificationClick"
                        >
                          {{ countDown > 0 ? `${countDown}秒后重试` : '获取验证码' }}
                        </span>
                      </template>
                    </el-input>
                  </template>
                  <template v-else>
                    <div class="slider-container">
                      <slide-verify
                          @success="handleSliderSuccess"
                          slider-text="向右滑动验证"
                      />
                    </div>
                  </template>
                </div>
              </div>
              <div class="step-actions">
                <el-button :disabled="nextStepDisabled" style="width: 100%" type="primary" @click="nextStep">下一步
                </el-button>
              </div>
            </div>

            <div v-if="activeStep === 2" class="step-container">
              <span class="dialog-body-title">绑定新手机号</span>
              <div class="form-container">
                <div class="phone-input-group">
                  <el-select v-model="countryCode" class="country-code">
                    <el-option label="+86" value="+86"/>
                  </el-select>
                  <el-input v-model="phoneNumber" placeholder="请输入新的手机号"/>
                </div>
                <div class="verification-input-group">
                  <el-input v-model="phoneVerificationCode" placeholder="请输入手机验证码"/>
                  <el-button
                      type="primary"
                      :disabled="countDown > 0"
                      @click="getPhoneVerificationCode"
                  >
                    {{ countDown > 0 ? `${countDown}秒后重试` : '获取验证码' }}
                  </el-button>
                </div>
              </div>
              <div class="step-actions">
                <el-button style="width: 100%" type="primary" @click="confirmChange">确认</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
.dialog-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2000;
}

.dialog-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-content {
  background-color: #fff;
  border-radius: 31px;
  overflow: hidden;
  animation: dialog-fade-in 0.3s;
}

.dialog-body {
  padding: 0 40px 24px;
}

.dialog-body-title {
  font-weight: 500;
  font-size: 20px;
  line-height: 28px;
  color: #1A1A1A;
}

@keyframes dialog-fade-in {
  0% {
    transform: translateY(-20px);
    opacity: 0;
  }
  100% {
    transform: translateY(0);
    opacity: 1;
  }
}

.form-container {
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.phone-input-group {
  display: flex;
  gap: 12px;
}

.country-code {
  width: 100px;
}

.verification-input-group {
  display: flex;
  gap: 12px;
}

:deep(.el-input__wrapper) {
  background-color: #F7F8FA;
  box-shadow: none !important;
  border: none;
}

:deep(.el-select .el-input__wrapper) {
  background-color: #F7F8FA;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409EFF inset !important;
}

.step-actions {
  margin-top: 32px;
  display: flex;
  justify-content: center;
  gap: 12px;
}

:deep(.el-button) {
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
}

:deep(.el-select .el-input .el-select__caret) {
  color: #86909C;
}

.steps {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px 40px;
  gap: 12px;
}

.step-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
}

.step-item.active {
  color: #409EFF;
}

.step-number {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #F2F6FC;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 500;
}

.step-item.active .step-number {
  background-color: #409EFF;
  color: white;
}

.step-text {
  font-size: 14px;
}

.step-line {
  flex: 1;
  height: 1px;
  background-color: #DCDFE6;
  position: relative;
}

.step-line::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background-color: #409EFF;
  transition: width 0.3s;
  width: v-bind('activeStep === 2 ? "100%" : "0"');
}

.verification-code-btn {
  color: #165DFF;
  cursor: pointer;
  font-size: 14px;
  user-select: none;
  padding: 0 4px;
}

.verification-code-btn:hover {
  opacity: 0.8;
}

.verification-code-btn.disabled {
  color: #C9CDD4;
  cursor: not-allowed;
}

.slider-container {
  width: 100%;
}

:deep(.slider-verify-container) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.slider-verify-slider) {
  border-radius: 4px;
  height: 36px !important;
  line-height: 36px !important;
}

:deep(.slider-verify-slider-mask) {
  height: 36px !important;
  border-radius: 4px;
}

:deep(.slider-verify-slider-icon) {
  height: 36px !important;
  width: 40px !important;
  border-radius: 4px;
}
</style>